﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Linq;
using YAPACS.BusinessObjects.Exams;
using YAPACS.BusinessObjects.Managements.Exams;
using YAPACS.Organizations;
using YAPACS.RisServer.Workflows.SyncData;

namespace YAPACS.RisServer.Controllers;

[Authorize]
public class ExamItemController(IRepository<ExamItem, Guid> examItemRepository, IGetExamItem getExamItem,
    ICurrentUserOrganization currentUser,
    IRepository<Department, Guid> departmentRepository, IAsyncQueryableExecuter queryableExecuter, IRepository<Exam, Guid> examRepository) : AbpControllerBase
{
    private readonly IRepository<ExamItem, Guid> _examItemRepository = examItemRepository;
    private readonly IGetExamItem _getExamItem = getExamItem;
    private readonly ICurrentUserOrganization _currentUser = currentUser;
    private readonly IRepository<Department, Guid> _departmentRepository = departmentRepository;
    private readonly IAsyncQueryableExecuter _queryableExecuter = queryableExecuter;
    private readonly IRepository<Exam, Guid> _examRepository = examRepository;

    [AllowAnonymous]
    [HttpGet]
    [Route("api/get-exam-items")]
    public async Task<IActionResult> GetExamItems([FromQuery] string departmentCode, [FromQuery] string deviceTypeCode)
    {
        try
        {
            var result = await _getExamItem.InvokeAsync(new YAPACS.Workflows.WorkflowInput()
        {
            {"DepartmentCode", departmentCode},
            {"DeviceTypeCode",deviceTypeCode }
        });
            return Ok(result);
        }
        catch (Exception ex)
        {
            return Ok(new { Success = false, Error = ex.Message });
        }
    }

    [HttpGet("api/[controller]/get-exam-items")]
    public async Task<IActionResult> GetExamItems()
    {
        var department = await _departmentRepository.GetAsync(_currentUser.DepartmentId.Value);
        var query = await _examItemRepository.GetQueryableAsync();
        query = query.Where(e => e.IsActive && e.Department == department && e.Parent == null).OrderBy(e => e.DeviceType);
        var examItemList = await _queryableExecuter.ToListAsync(query);
        JArray examItems = [];
        foreach (var item in examItemList)
        {
            var childrenArray = BuildItemTreeAsync(item);
            examItems.Add(new
            {
                Label = item.Name,
                Value = item.Oid,
                Children = childrenArray
            });
        }
        return Ok(examItems);
    }

    /// <summary>
    /// 构建检查项目树
    /// </summary>
    /// <param name="examItem"></param>
    /// <returns></returns>
    private List<object> BuildItemTreeAsync(ExamItem examItem)
    {
        List<object> tree = [];
        var children = examItem.Children;
        foreach (var item in children)
        {
            var childrenArray = BuildItemTreeAsync(item);
            tree.Add(new
            {
                Label = item.Name,
                Value = item.Oid,
                Children = childrenArray
            });
        }
        return tree;
    }

    [HttpGet("api/[controller]/get-exam-items-by-exam/{examId}")]
    public async Task<IActionResult> GetExamItemsByExam(Guid examId)
    {
        try
        {
            var exam = await _examRepository.GetAsync(examId);
            var list = exam.ExamItems.Select(e => new
            {
                e.Oid,
                e.Code,
                Name = e.GetShortName(),
                SharedSign = e.IsShared ? e.SharedSign : null,
            }).ToList();
            return Ok(new { Success = true, Data = new { Rows = list, TotalCount = list.Count } });
        }
        catch (Exception ex)
        {
            return Ok(new { Success = false, Error = ex.Message });
        }
    }
}
